const app = getApp();
const http = require("../../config/api.js");
const user = require("../../utils/login.js");
Page({
  data: {
    videoContext: '',
    showVideoType: 'start',//trySee：试看；start开始；空为隐藏,

    pageData: {},
    videoIndex: 0,//当前播放第几集
    hideDetail: false,//展示详情
    albumCode: '',//专辑编码
    projectCode: "lyhad",
    baseUrlImg: app.globalData.baseUrlImg,
    isVIP: '',
    _index: true, //用来做停止播放的
    log: {
      STOP_TIME: null
    },
    play: false, // 记录停止播放或者切换
  },
  onLoad: function (options) {
    this.setData({
      albumCode: options.code
    });
    if (wx.getStorageSync('openid')) {
      this.setData({
        isVIP: wx.getStorageSync('isVIP')
      })
      this.getAlbumResList();
    } else {
      user.getLogin().then(res => {
        this.setData({
          isVIP: wx.getStorageSync('isVIP')
        })
        this.getAlbumResList();
      })
    }
  },
  onShow:function() {
    let time = Math.round(new Date().getTime());
    let log = {
      //日志类型：unite.通用业务；visit.访问数据；click.点击数据；order.订购数据；error.错误日志
      logType: "visit",
      msg: JSON.stringify({
        mac: app.globalData.userId,
        page: "xcxzjinfo",
        pageName: "梨园行专辑详情",
        time: time,
        appVersionName: "小程序",
        item: 65,
        nodeCode: "001000",
        project: "lyhad",
        userId: app.globalData.memberId,
        deviceId: app.globalData.userId,
        uuid: user.getUuid(),
        pageLevel: "1"
      })
    }
    this.uniteLog(log)
  },
  onReady(res) {
    this.videoContext = wx.createVideoContext('myVideo')
  },
  //切换选集
  switchVideo:function(e){
    let index = e.currentTarget.dataset.idx || 0;
    if(this.data.play) {
      this.addHistory(this.data.log.STOP_TIME)
    }
    this.setData({
      showVideoType: 'start',
      videoIndex: index,
      play: false,
      ['log.STOP_TIME']: null
    });
    if (!this.data.pageData.pb.dataList[index].playurl){
      this.fnGetPlayUrl(this.data.pageData.pb.dataList[index].code);
    }

  },
  // 调用删除接口
  delCollection: function (idx) {
    let userData = wx.getStorageSync('openid') || '{}';
    userData = JSON.parse(userData);
    console.log(userData);
    let data = {
      userId: userData.openId || '',
      resType: 5,
      range: 0,
      project: "lyhad",
      codes: [this.data.albumCode],//资源编码（数组）；空为全部删除
    }

    http.lhxRequest("api_delUserStore", data).then(res => {
      if (res.code === 10000000) {
        wx.showToast({
          title: '删除成功',
          icon: 'none',
          duration: 2000
        })
        this.setData({
          ["pageData.album.flag"]: this.data.pageData.album.flag == 1 ? 0 : 1
        });
      }
    })
  },
  // 添加收藏
  collection: function(){
    if (this.data.pageData.album.flag!=1){
      let userData = wx.getStorageSync('openid') || '{}';
      userData = JSON.parse(userData);
      let data = {
        userId: userData.openId || '',
        resType: 5,
        resCode: this.data.albumCode,
        project: this.data.projectCode,
        item: 65,
        limitNum: 0, //不限制
      }
      
      http.lhxRequest("api_addUserStore", data).then(res => {
        if (res.code === 10000000) {
          wx.showToast({
            title: '已添加到收藏，可在"我的"页面查看',
            icon: "none",
            duration: 3000,
          });
          this.setData({
            ["pageData.album.flag"]: this.data.pageData.album.flag == 1 ? 0 : 1
          });
        }
      })
      
    }
  },
  //展示详情
  changeDetail:function(){
    
    this.setData({
      hideDetail: !this.data.hideDetail
    });
  },
  //读取数据
  getAlbumResList: function(){
    let userData = wx.getStorageSync('openid') || '{}';
    userData = JSON.parse(userData);
    let data = {
      streamNo:"",//请求流水号（前端无需填写）
      albumCode: this.data.albumCode,//专辑编码
      selectFlag: "",//选段类型：0.全部1选段2剧集
      userId: userData.openId || '',//用户业务账号：普通用户（未登录）/ 会员（已登录）
      project: this.data.projectCode,//产品编码
      px: "",//分辨率：1.标清；2.高清
      cur: 1,//表示当前请求页码
      pageSize: 10000,//	表示分页大小
    }
    http.lhxRequest("api_getAlbumResList", data).then(res => {
      if (res.code === 10000000) {
        this.setData({
          pageData: res
        })
        if (this.data.pageData.pb.dataList && this.data.pageData.pb.dataList.length>0){
          this.fnGetPlayUrl(this.data.pageData.pb.dataList[0].code);
        }
      }
    })
  },
  // 获取视频数据
  fnGetPlayUrl(codeStr) {
    let userData = wx.getStorageSync('openid') || '{}';
    userData = JSON.parse(userData);
    let code = codeStr || '';
    let data = {
      userId: userData.openId || '',
      resCode: code,
      px: 2,
      item: 65
    }
    http.lhxRequest("api_getPlayUrl", data).then(res => {
      if (res.code === 10000000) {
        let list = this.data.pageData.pb.dataList;
        for (let i in list) {
          list[i].playurl = "";
          if (list[i].code == code) {
            console.log(res.playres.playurl)
            list[i].playurl = res.playres.playurl
            //indexList[i].playurl = "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
          }
        }
        this.setData({
          ['pageData.pb.dataList']: list
        })
        console.log(this.data.pageData.pb.dataList[this.data.videoIndex].playurl);
        // let videoContext = wx.createVideoContext(this.data.myVideo);
        // console.log(this.data.myVideo)
        // videoContext.play();
      }
    })
  },
  // 添加播放记录 
  addHistory(stop) {
    let userData = wx.getStorageSync('openid') || '{}';
    userData = JSON.parse(userData);
    let code = this.data.pageData.pb.dataList[this.data.videoIndex].code || '';
    let aTime = this.data.pageData.pb.dataList[this.data.videoIndex].allTime || 0;
    let timeStop = stop || null;
    let data = {
      userId: userData.openId || '',
      resType: 1,
      resCode: code,
      allTime: aTime,
      project: 'lyhad',
      entryId: '1',
      item: "65",
      sourceType: "105",
      sourceValue: this.data.pageData.album.code
    }
    if (timeStop) { data.timeStop = timeStop }
    http.lhxRequest("api_addUserPlayLog", data).then(res => {
      if (res.code === 10000000) {
        console.log('添加播放记录');
      }
    })
  },
  playVideo: function(){
    let record = { 
      img: this.data.pageData.album.img,//展示封面图
      name: this.data.pageData.album.name,//剧名
      code: this.data.pageData.album.code,//专辑code
      freeFlag: this.data.pageData.album.freeFlag,//是否免费
      totalNum: this.data.pageData.album.totalNum,//总共几集
    };
    if (!wx.getStorageSync('openid')){
      app.recordHistory(record);
    }else{
      this.addHistory();
    }
    this.setData({
      showVideoType: '',
      play: true
    });
    this.videoContext.play();
  },
  videoTimeupdate: function(e){
    if (!this.data_index) {
      this.setData({
        ['log.STOP_TIME']: e.detail.currentTime,//停止播放得时间
      })
    }
    if (!this.data.isVIP && this.data.pageData.album.freeFlag==0){
      if (e.detail.currentTime >= 180) {
        this.setData({
          showVideoType: 'trySee'
        });
        this.videoContext.pause();
      }
    }
  },
  videoEnded: function(){
    this.setData({
      showVideoType: 'start'
    });
  },
  onShareAppMessage: function () {
    return {
      title: this.data.pageData.album.name || '',
      imageUrl: !this.data.pageData.album ? '' : this.data.baseUrlImg + (this.data.pageData.album.img || '')
    }
  },
  // 日志
  uniteLog(data) {
    http.lhxRequest("api_log", data).then(res => {
      if (res.code === 10000000) {
        console.log("日志")
      }
    })
  },
  onUnload: function() {
    this.setData({
      _index: null
    })
    this.addHistory(this.data.log.STOP_TIME)
  }
})